#!/bin/bash

CMAPI_KEY="${CMAPI_KEY:-somekey123}"
IFLAG='/etc/columnstore/container-initialized'
MAX_USER="${MAX_USER:-maxscale}"
MAX_PASS="${MAX_PASS:-C0lumnStore!}"
REP_USER="${REP_USER:-idbrep}"
REP_PASS="${REP_PASS:-C0lumnStore!}"
CLUSTER="${CLUSTER:-false}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

CMAPI="curl --write-out '%{http_code}' --silent --output /dev/null -X PUT https://${PM1}:8640/cmapi/0.4.0/cluster"
MAXAPI1="curl --write-out '%{http_code}' --silent --output /dev/null -X POST -u admin:mariadb ${MX1}:8989/v1"
MAXAPI2="curl --write-out '%{http_code}' --silent --output /dev/null -X POST -u admin:mariadb ${MX2}:8989/v1"

HEADER1="'Content-Type:application/json'"
HEADER2="'x-api-key:$CMAPI_KEY'"

PAYLOAD1='{"timeout":60, "node": "'$PM1'"}'
PAYLOAD2='{"timeout":60, "node": "'$PM2'"}'
PAYLOAD3='{"timeout":60, "node": "'$PM3'"}'
PAYLOAD4='{"data":{"id":"pm3","type":"servers","attributes":{"parameters":{"address":"'$PM3'","protocol":"MariaDBBackend"}}}}'
PAYLOAD5='{"data":{"id":"pm2","type":"servers","attributes":{"parameters":{"address":"'$PM2'","protocol":"MariaDBBackend"}}}}'
PAYLOAD6='{"data":{"id":"pm1","type":"servers","attributes":{"parameters":{"address":"'$PM1'","protocol":"MariaDBBackend"}}}}'
PAYLOAD7='{"data":{"id":"mcs_service","type":"services","attributes":{"router":"readwritesplit","parameters":{"user":"'$MAX_USER'","password":"'$MAX_PASS'","master_accept_reads":true}},"relationships":{"servers":{"data":[{"id":"pm1","type":"servers"},{"id":"pm2","type":"servers"},{"id":"pm3","type":"servers"}]}}}}'
PAYLOAD8='{"data":{"id":"mcs_listener","type":"listeners","attributes":{"parameters":{"protocol":"MariaDBClient","port":3306}},"relationships":{"services":{"data":[{"id":"mcs_service","type":"services"}]}}}}'
PAYLOAD9='{"data":{"id":"mcs_monitor","type":"monitors","attributes":{"module":"mariadbmon","parameters":{"user":"'$MAX_USER'","password":"'$MAX_PASS'","replication_user":"'$REP_USER'","replication_password":"'$REP_PASS'","enforce_read_only_slaves":true,"auto_failover":true,"auto_rejoin":true,"cooperative_monitoring_locks":"majority_of_all"}},"relationships":{"servers":{"data":[{"id":"pm1","type":"servers"},{"id":"pm2","type":"servers"},{"id":"pm3","type":"servers"}]}}}}'

RESOURCE1='node'
RESOURCE2='servers'
RESOURCE3='services'
RESOURCE4='listeners'
RESOURCE5='monitors'

MODULES=("$CMAPI/$RESOURCE1 --header $HEADER1 --header $HEADER2 --data '$PAYLOAD1' -k" "$CMAPI/$RESOURCE1 --header $HEADER1 --header $HEADER2 --data '$PAYLOAD2' -k" "$CMAPI/$RESOURCE1 --header $HEADER1 --header $HEADER2 --data '$PAYLOAD3' -k")

SERVERS1=("$MAXAPI1/$RESOURCE2 -d '$PAYLOAD4'" "$MAXAPI1/$RESOURCE2 -d '$PAYLOAD5'" "$MAXAPI1/$RESOURCE2 -d '$PAYLOAD6'")
SERVICE1="$MAXAPI1/$RESOURCE3 -d '$PAYLOAD7'"
LISTENER1="$MAXAPI1/$RESOURCE4 -d '$PAYLOAD8'"
MONITOR1="$MAXAPI1/$RESOURCE5 -d '$PAYLOAD9'"

SERVERS2=("$MAXAPI2/$RESOURCE2 -d '$PAYLOAD4'" "$MAXAPI2/$RESOURCE2 -d '$PAYLOAD5'" "$MAXAPI2/$RESOURCE2 -d '$PAYLOAD6'")
SERVICE2="$MAXAPI2/$RESOURCE3 -d '$PAYLOAD7'"
LISTENER2="$MAXAPI2/$RESOURCE4 -d '$PAYLOAD8'"
MONITOR2="$MAXAPI2/$RESOURCE5 -d '$PAYLOAD9'"

# Wait For Primary Node To Start
if [ ! -f $IFLAG ]; then
    echo -n 'Waiting for PM1 to be initialized '
    while [ ! -f $IFLAG ]
    do
        printf "."
        sleep 2
    done
    printf " ${GREEN}done${NC}\n"
fi

sleep 3

if [[ $CLUSTER == false ]]; then
    # If Standalone Server Add Single Node
    RESULT0=$(bash -c "${MODULES[0]}")
    if [[ "$RESULT0" == 200 ]]; then
        printf "Adding PM1 to CMAPI ... ${GREEN}done${NC}\n"
    else
        printf "Adding PM1 to CMAPI ... ${RED}fail${NC}\n"
        exit 1
    fi
else
    # Else Add Multiple Nodes Cluster
    count=1
    for i in "${MODULES[@]}"
    do
        RESULT1=$(bash -c "$i")
        if [[ "$RESULT1" == 200 ]]; then
            printf "Adding PM$count to CMAPI ... ${GREEN}done${NC}\n"
        else
            printf "Adding PM$count to CMAPI ... ${RED}fail${NC}\n"
            exit 1
        fi
        (( count++ ))
    done

    # Add Servers To MaxScale 1
    count=1
    for i in "${SERVERS1[@]}"
    do
        RESULT1=$(bash -c "$i")
        if [[ "$RESULT1" == 403 ]]; then
            printf "Adding PM$count to MaxScale 1 ... ${YELLOW}already exists${NC}\n"
        else
            if [[ "$RESULT1" == 204 ]]; then
                printf "Adding PM$count to MaxScale 1 ... ${GREEN}done${NC}\n"
            else
                printf "Adding PM$count to MaxScale 1 ... ${RED}fail${NC}\n"
                exit 1
            fi
        fi
        (( count++ ))
    done

    # Add Servers To MaxScale 2
    count=1
    for i in "${SERVERS2[@]}"
    do
        RESULT1=$(bash -c "$i")
        if [[ "$RESULT1" == 403 ]]; then
            printf "Adding PM$count to MaxScale 2 ... ${YELLOW}already exists${NC}\n"
        else
            if [[ "$RESULT1" == 204 ]]; then
                printf "Adding PM$count to MaxScale 2 ... ${GREEN}done${NC}\n"
            else
                printf "Adding PM$count to MaxScale 2 ... ${RED}fail${NC}\n"
                exit 1
            fi
        fi
        (( count++ ))
    done

    # Add Router To MaxScale 1
    RESULT2=$(bash -c "$SERVICE1")
    if [[ "$RESULT2" == 403 ]]; then
        printf "Adding SERVICE to MaxScale 1 ... ${YELLOW}already exists${NC}\n"
    else
        if [[ "$RESULT2" == 204 ]]; then
            printf "Adding SERVICE to MaxScale 1 ... ${GREEN}done${NC}\n"
        else
            printf "Adding SERVICE to MaxScale 1 ... ${RED}fail${NC}\n"
            exit 1
        fi
    fi

    # Add Router To MaxScale 2
    RESULT2=$(bash -c "$SERVICE2")
    if [[ "$RESULT2" == 403 ]]; then
        printf "Adding SERVICE to MaxScale 2 ... ${YELLOW}already exists${NC}\n"
    else
        if [[ "$RESULT2" == 204 ]]; then
            printf "Adding SERVICE to MaxScale 2 ... ${GREEN}done${NC}\n"
        else
            printf "Adding SERVICE to MaxScale 2 ... ${RED}fail${NC}\n"
            exit 1
        fi
    fi

    # Add Listener To MaxScale 1
    RESULT3=$(bash -c "$LISTENER1")
    if [[ "$RESULT3" == 403 ]]; then
        printf "Adding LISTENER to MaxScale 1 ... ${YELLOW}already exists${NC}\n"
    else
        if [[ "$RESULT3" == 204 ]]; then
            printf "Adding LISTENER to MaxScale 1 ... ${GREEN}done${NC}\n"
        else
            printf "Adding LISTENER to MaxScale 1 ... ${RED}fail${NC}\n"
            exit 1
        fi
    fi

    # Add Listener To MaxScale 2
    RESULT3=$(bash -c "$LISTENER2")
    if [[ "$RESULT3" == 403 ]]; then
        printf "Adding LISTENER to MaxScale 2 ... ${YELLOW}already exists${NC}\n"
    else
        if [[ "$RESULT3" == 204 ]]; then
            printf "Adding LISTENER to MaxScale 2 ... ${GREEN}done${NC}\n"
        else
            printf "Adding LISTENER to MaxScale 2 ... ${RED}fail${NC}\n"
            exit 1
        fi
    fi

    # Add Monitor To MaxScale 1
    RESULT4=$(bash -c "$MONITOR1")
    if [[ "$RESULT4" == 403 ]]; then
        printf "Adding MONITOR to MaxScale 1 ... ${YELLOW}already exists${NC}\n"
    else
        if [[ "$RESULT4" == 204 ]]; then
            printf "Adding MONITOR to MaxScale 1 ... ${GREEN}done${NC}\n"
        else
            printf "Adding MONITOR to MaxScale 1 ... ${RED}fail${NC}\n"
            exit 1
        fi
    fi

    # Add Monitor To MaxScale 2
    RESULT4=$(bash -c "$MONITOR2")
    if [[ "$RESULT4" == 403 ]]; then
        printf "Adding MONITOR to MaxScale 2 ... ${YELLOW}already exists${NC}\n"
    else
        if [[ "$RESULT4" == 204 ]]; then
            printf "Adding MONITOR to MaxScale 2 ... ${GREEN}done${NC}\n"
        else
            printf "Adding MONITOR to MaxScale 2 ... ${RED}fail${NC}\n"
            exit 1
        fi
    fi
fi

sleep 5
printf "Sleeping 5 seconds ... ${GREEN}done${NC}\n"

# Validate
QUERY=$(mariadb -sN -e "DROP DATABASE IF EXISTS validate; CREATE DATABASE validate; CREATE TABLE validate.sample (id INT) ENGINE=columnstore; INSERT INTO validate.sample VALUES (99); SELECT id FROM validate.sample;" 2>&1)
if [ $? = 0 ] && [ $QUERY = 99 ]; then
    printf "Validating ColumnStore engine ... ${GREEN}done${NC}\n"
    mariadb -e "DROP DATABASE IF EXISTS validate;" 2>&1
else
    printf "Validating ColumnStore engine ... ${RED}fail${NC}\n"
    exit 1
fi

unset REP_USER
unset REP_PASS
unset MAX_USER
unset MAX_PASS
